package com.atguigu.szdz.dcsyl.controller;

import com.alibaba.excel.EasyExcel;
import com.atguigu.szdz.dcsyl.common.listener.FcListener;
import com.atguigu.szdz.dcsyl.common.utils.R;
import com.atguigu.szdz.dcsyl.entity.FcDataEntity;
import com.atguigu.szdz.dcsyl.service.impl.YlDataServiceImpl;
import com.atguigu.szdz.dcsyl.utils.MapperUtils;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/fcData")
public class FcDataController {
    @Autowired
    private YlDataServiceImpl fcDataService;
    @Autowired
    private MapperUtils mapperUtils;

    /**
     * 获取分层数据
     *
     * @param map
     * @return
     */
    @RequestMapping("/getFcData")
    public R getFcData(@RequestBody Map<String, Integer> map) {
        //获取井ID
        Integer wellId = map.get("wellId");
        //获取当前页
        Integer currentPage = map.get("currentPage");
        //获取每页显示条数
        Integer pageSize = map.get("pageSize");
        //获取总条数
        String sql = "select count(*) from dc_fcdata where well_id=" + wellId;
        List<Map<String, Object>> contList = mapperUtils.queryBySql(sql);
        Integer total = Integer.parseInt(contList.get(0).get("count").toString());
        //总页数
        Integer totalPage = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
        //获取数据
        List<Map<String, Object>> fcListData = fcDataService.getFcData(wellId, currentPage, pageSize);
        return R.ok().put("fcListData", fcListData).put("total", total).put("totalPage", totalPage);
    }

    /**
     * 导入分层的excel文件
     *
     * @param file
     * @param wellId
     * @return
     */
    @Operation(summary = "导入分层的excel文件并解析")
    @PostMapping("/importFile")
    public R importFile(@RequestParam("file") MultipartFile file, @RequestParam("well_id") Integer wellId) {
        //先去数据库查询是否有该井
        String sql = "select * from dc_well_info where id=" + wellId;
        List<Map<String, Object>> wellList = mapperUtils.queryBySql(sql);
        //获取井名
        String wellName = wellList.get(0).get("well_name").toString();
        List<FcDataEntity> list = new ArrayList<>();
        if (wellList.size() == 0) {
            return R.error("井不存在");
        }
        if (file.isEmpty()) {
            return R.error("文件不能为空");
        }
        String fileName = file.getOriginalFilename();
        if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) {
            return R.error("文件格式错误");
        }
        try (InputStream inputStream = file.getInputStream()) {
            FcListener fcDataListener = new FcListener();
            //解析excel文件
            EasyExcel.read(inputStream, FcDataEntity.class, fcDataListener).headRowNumber(2).sheet().doRead();
            //获取读到的数据
            list = fcDataListener.getList();
            //判断读出来的井名和选择的井名是否相同
            if (!list.get(0).getWellName().equals(wellName)) {
                return R.error("井名不一致,请重新上传");
            } else {
                //返回数据
                return R.ok().put("fcListData", list);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("文件导入失败");
        }
    }

    /**
     * 导入分层数据
     *
     * @param map
     * @return
     */
    @Operation(summary = "导入分层数据")
    @PostMapping("/importFcData")
    public R importFcData(@RequestBody Map<String, Object> map) {
        //获取井ID
        Integer wellId = Integer.parseInt(map.get("wellId").toString());
        //获取数据vo->po
        List<FcDataEntity> list = new ArrayList<>();
        List<Map<String, Object>> fcListData = (List<Map<String, Object>>) map.get("fcListData");
        for (Map<String, Object> fcMap : fcListData) {
            FcDataEntity fcDataEntity = new FcDataEntity();
            //转换
            fcDataEntity.setWellName(fcMap.get("wellName") != null ? fcMap.get("wellName").toString() : null);
            fcDataEntity.setName(fcMap.get("name") != null ? fcMap.get("name").toString() : null);
            fcDataEntity.setTopDepth(fcMap.get("topDepth") != null ? Double.parseDouble(fcMap.get("topDepth").toString()) : null);
            fcDataEntity.setBottomDepth(fcMap.get("bottomDepth") != null ? Double.parseDouble(fcMap.get("bottomDepth").toString()) : null);
            fcDataEntity.setThickness(fcMap.get("thickness") != null ? Double.parseDouble(fcMap.get("thickness").toString()) : null);
            fcDataEntity.setVerticalTopDepth(fcMap.get("verticalTopDepth") != null ? Double.parseDouble(fcMap.get("verticalTopDepth").toString()) : null);
            fcDataEntity.setVerticalBottomDepth(fcMap.get("verticalBottomDepth") != null ? Double.parseDouble(fcMap.get("verticalBottomDepth").toString()) : null);
            fcDataEntity.setVerticalThickness(fcMap.get("verticalThickness") != null ? Double.parseDouble(fcMap.get("verticalThickness").toString()) : null);
            fcDataEntity.setPlanActual(fcMap.get("planActual") != null ? fcMap.get("planActual").toString() : null);
            fcDataEntity.setLevel(fcMap.get("level") != null ? fcMap.get("level").toString() : null);
            fcDataEntity.setRemark(fcMap.get("remark") != null ? fcMap.get("remark").toString() : null);
            list.add(fcDataEntity);
        }
        //先删除该井的所有数据
        fcDataService.removeFcData(wellId);
        //批量插入数据库
        fcDataService.saveBatchFc(list, wellId);
        return R.ok();
    }
}
